<?php

namespace app;

use think\Controller;

/**
 * 公共类
 * 系统所有的公共方法都在这
 */
class Api extends Controller
{
    protected $_now;//当前时间

    public function _initialize()
    {
        parent::_initialize();
        header("Access-Control-Allow-Origin: *");//允许跨域
        $this->_now = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']); // 服务器收到请求的时间，即当前时间timestamp
    }

    /**
     * 将xml转换成php数组
     * @param string $xml
     * @return mixed
     */
    protected function xmlToArray($xml)
    {

        //禁止引用外部xml实体

        libxml_disable_entity_loader(true);

        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

        $val = json_decode(json_encode($xmlstring), true);

        return $val;

    }

    /**
     * 模拟GET表单提交
     * @access protected
     * @param string $url 链接
     * @since 1.0
     * @return string
     */
    protected function _curlGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $info = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error' . curl_error($ch);
        }
        curl_close($ch);
        return $info;
    }

    /**
     * 获取随机字符串
     * @access protected
     * @param int $n 随机数的长度(默认32位)
     * @since 1.0
     * @return string
     */
    protected function _getRandomString($n = 32)
    {
        $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';//输出字符集
        $len = strlen($str) - 1;
        $s = '';
        for ($i = 0; $i < $n; $i++) {
            $s .= $str[rand(0, $len)];
        }
        return $s;
    }

    /**
     * 获取IP地址
     * @access public
     * @since 1.0
     * @return string
     */
    protected function getIP()
    {
        global $ip;
        if (getenv("HTTP_CLIENT_IP"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR"))
            $ip = getenv("REMOTE_ADDR");
        else $ip = '';
        return $ip;
    }


    /**
     * 获取数组的部分指定数据
     * @param array $array
     * @param int $firstRow
     * @param int $listRows
     * @return array
     */
    protected function getArray($array, $firstRow, $listRows)
    {
        $finishRows = $firstRow + $listRows;
        $arr = [];
        for ($i = $firstRow; $i < $finishRows; $i++) {
            if (isset($array[$i])) {
                $arr[] = $array[$i];
            }
        }
        return $arr;
    }


    /**
     * 根据两点间的经纬度计算距离
     * @access protected
     * @param float $lat1 纬度值1
     * @param float $lng1 经度值1
     * @param float $lat2 纬度值2
     * @param float $lng2 经度值2
     * @return float
     */
    protected function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        $earthRadius = 6367000; //近似地球半径米

        /*这些学位转换为弧度使用这个公式*/
        $lat1 = ($lat1 * pi()) / 180;
        $lng1 = ($lng1 * pi()) / 180;

        $lat2 = ($lat2 * pi()) / 180;
        $lng2 = ($lng2 * pi()) / 180;

        /*使用半正矢公式http://en.wikipedia.org/wiki/Haversine_formula计算距离*/
        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;

        return round($calculatedDistance);
    }

    /**
     * 模拟表单提交
     * @access protected
     * @param string $url 链接
     * @param array|string $data 数据
     * @since 1.0
     * @return string
     */
    protected function _curlPost($url, $data, $header = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $info = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Errno' . curl_error($ch);
        }
        curl_close($ch);
        return $info;
    }

    /**
     * 生成指定位数的随机数字
     * @param string $title 前缀
     * @param int $length 长度
     * @return bool|string
     */
    protected function _makeSerialNumber($title = '', $length = 32)
    {
        if (intval($length) < 20) return false;
        $length -= 16;
        while (true) {
            $order_id_main = date('YmdHis') . rand(pow(10, ($length - 1)), pow(10, $length) - 1);
            $order_id_len = strlen($order_id_main);
            $order_id_sum = 0;
            for ($i = 0; $i < $order_id_len; $i++) {
                $order_id_sum += (int)(substr($order_id_main, $i, 1));
            }
            $order_id = $title . $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
            return $order_id;
        }
    }
}
